#include "button.h"
#include "systimer.h"
#include "buzzer.h"
#include <stdio.h>

static Button button[BUTTON_NUM] = {
    {Btn_Power, Release, 5, 0, 20, 3000,   0, 0, GPIOB, GPIO_PIN_15},
    {Btn_Mode,  Release, 5, 0, 20, 6000,   0, 0, GPIOB, GPIO_PIN_14},
    {Btn_Speed, Release, 5, 0, 20, 65535,  0, 0, GPIOB, GPIO_PIN_13},
    {Btn_Down,  Release, 5, 0, 20, 6000,   0, 0, GPIOB, GPIO_PIN_12},
    {Btn_Up,    Release, 5, 0, 20, 6000,   0, 0, GPIOB, GPIO_PIN_2},
    {Btn_Page,  Release, 5, 0, 20, 65535,  0, 0, GPIOB, GPIO_PIN_1}
};

void button_init(void)
{
    rcu_periph_clock_enable(RCU_GPIOB);
    gpio_init(button[Btn_Power].gpio_periph, GPIO_MODE_IPU, GPIO_OSPEED_2MHZ, button[Btn_Power].pin);
    gpio_init(button[Btn_Mode].gpio_periph,  GPIO_MODE_IPU, GPIO_OSPEED_2MHZ, button[Btn_Mode].pin);
    gpio_init(button[Btn_Speed].gpio_periph, GPIO_MODE_IPU, GPIO_OSPEED_2MHZ, button[Btn_Speed].pin);
    gpio_init(button[Btn_Down].gpio_periph,  GPIO_MODE_IPU, GPIO_OSPEED_2MHZ, button[Btn_Down].pin);
    gpio_init(button[Btn_Up].gpio_periph,    GPIO_MODE_IPU, GPIO_OSPEED_2MHZ, button[Btn_Up].pin);
    gpio_init(button[Btn_Page].gpio_periph,  GPIO_MODE_IPU, GPIO_OSPEED_2MHZ, button[Btn_Page].pin);
}

void button_scan(void)
{
    uint8_t buzzerState = 0;

    for(uint8_t i = 0; i < BUTTON_NUM; i++)
    {
        /* 未生成键值 */
        if(button[i].flag == 0)
        {
            /* 按键按下 */
            if(gpio_input_bit_get(button[i].gpio_periph, button[i].pin) == 0)
            {
                button[i].pressTimeSum += button[i].pressTimeOnce;
                if(button[i].pressTimeSum >= button[i].longPressTimeMin)
                {
                    button[i].state = LongPressed;
                    button[i].flag = 1;
                    button[i].buzzerCnt = 10;
                }
            }
            /* 按键松开 */
            else
            {
                if(button[i].pressTimeSum >= button[i].pressTimeMin)
                {
                    button[i].state = Pressed;
                    button[i].flag = 1;
                    button[i].buzzerCnt = 10;
                }
                else
                {
                    button[i].pressTimeSum = 0;
                    button[i].flag = 0;
                }
            }
        }
        /* 已生成键值 */
        else
        {
            /* 按键松开 */
            if(gpio_input_bit_get(button[i].gpio_periph, button[i].pin) != 0)
            {
                button[i].pressTimeSum = 0;
                button[i].flag = 0;
            }
        }
        /* 蜂鸣器 */
        if(button[i].buzzerCnt)
        {
            button[i].buzzerCnt--;
            buzzerState = 1;
        }
    }
    
    buzzer_set(buzzerState);
}

BtnState button_get_state(uint8_t id)
{
    BtnState state = button[id].state;
    if(state != Release)
    {
        button[id].state = Release;
    }
    return state;   
}

